package com.alianzamedica.controllers.drug;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Drug;
import com.alianzamedica.controllers.constants.ActionConstants;
import com.alianzamedica.tools.Enviroment;

/**
 * @author Carlos
 * 
 */
public class ListDrugAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		String nombre = request.getParameter("nombre");
		String sPageNum = request.getParameter("pageNum");
		Integer pageNum = 1;
		if (sPageNum != null && sPageNum.trim().length() > 0) {
			try {
				pageNum = Integer.valueOf(sPageNum);
			} catch (Exception e) {
			}
		}
		Drug d = new Drug();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		search.setDefaultDialect(ObjectSearch.MYSQL_DIALECT);
		search.setLike(true);
		if (nombre != null && nombre.trim().length() > 0) {
			d.setName(nombre);
		}
		ArrayList doctors = search.getPagedQuery(d, null, pageNum, ActionConstants.PAGE_SIZE);
		request.setAttribute("drugs", doctors);
		Integer totalPages = search.getTotalPages(d);
		request.setAttribute("totalPages", totalPages);

		return mapping.findForward("success");
	}

}
